//
//  XGIllnessTVC.m
//  kuaiyi
//
//  Created by 蒋小哥 on 16/7/6.
//  Copyright © 2016年 Alphts. All rights reserved.
//

/**
 *  添加病例VC
 */

#import "XGIllnessVC.h"
#import "XGAddCaseVC.h"
#import "SEIllReportModel.h"
#import <SVProgressHUD.h>
#import "SECaseManagerController.h"
#import "SECassDataMArr.h"
//存储数据的路径
#define kFilePath(fileName) ([NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:fileName])

@interface XGIllnessVC ()<XGAddCaseVCDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>


//照片imageView
@property (nonatomic, strong)UIImageView * imgv_photo;

//病症描述的textView
@property (nonatomic, strong)UITextView * caseTextView;

//记录text的文字
@property (nonatomic, copy)NSString * caseString;

//疾病类型
@property (nonatomic, copy)NSString * cassType;

//疾病细分
@property (nonatomic, copy)NSString * cassSmallType;

//photo的name
@property (nonatomic, copy)NSString * photoName;

@end

@implementation XGIllnessVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    self.title = @"增加病例";
   
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.tableView setSeparatorColor:[UIColor blackColor]];
    
    //添加提交按钮
    UIButton * btn_post = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 50)];
    [btn_post setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [btn_post setTitle:@"提交" forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:btn_post];
    //添加点击事件
    [btn_post addTarget:self action:@selector(clickCommit) forControlEvents:UIControlEventTouchUpInside];
    
    //修改箭头
//    [self setUpLeftButtonItem];
    
    //监听病症描述的文字是否改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCaseDescription) name:@"UITextViewTextDidChangeNotification" object:nil];
    //监听病症描述的文字即将编辑,判断是否选择了疾病细分,没有则不能编辑
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cassTextViewWillBeginEditing) name:@"UITextViewTextDidBeginEditingNotification" object:nil];
    [self.caseTextView setEditable:YES];
    [self.tableView reloadData];
}

  //MARK:提交按钮的点击事件
- (void)clickCommit {
    NSString * alertStr = nil;
    //判断必要的内容是否添加
    if (self.cassType.length > 0) {
        
        if (self.cassSmallType.length > 0) {
            //添加了疾病类型,可以保存数据
            SEIllReportModel * model = [SEIllReportModel new];
            model.cassBigType = self.cassType;
            model.cassSmallType = self.cassSmallType;
            model.cassDescription = self.caseString;
            
            //判断是否要传递照片
            if ([self.photoName isEqualToString:@"compose_pic_add_highlighted"]) {
                model.cassPhoto = nil;
            }else{
                model.cassPhoto = self.imgv_photo.image;
            }
            
            //获取当前时间
            NSDate * date = [NSDate date];
            NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
            
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *  commitTime = [formatter stringFromDate:date];
            
            model.commitTime = commitTime;
            
           NSString * filePath = kFilePath(@"XGIllCaseReprot.data");
            //先解档,取出原有数据
            SECassDataMArr * oldMutabltArr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
            
            //存储现有新数据
            if (oldMutabltArr == nil || oldMutabltArr.count == 0) {
                oldMutabltArr = (SECassDataMArr *)[NSMutableArray array];
            }
            
            //拼接数组后存储
            [oldMutabltArr insertObject:model atIndex:0];
            [NSKeyedArchiver archiveRootObject:oldMutabltArr toFile:filePath];
            //让上一个控制器刷新
            if (self.updateDataBlock) {
                self.updateDataBlock(model);
            }
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }else {
            //提醒添加疾病类型
            alertStr = @"请先添加疾病细分";
        }
        
    }else {
        //弹窗提醒添加疾病细分
        alertStr = @"请先添加疾病类型";
    }

    [SVProgressHUD showInfoWithStatus:alertStr];
    [SVProgressHUD setFadeOutAnimationDuration:0.5];
    [SVProgressHUD setFadeInAnimationDuration:0];
    [SVProgressHUD dismissWithDelay:1];
    
}

#pragma mark: - 通知中心监听事件的方法
//存储病例到字符串
- (void)getCaseDescription {
    self.caseString = [NSString stringWithString:self.caseTextView.text];
}
//判断textView是否可以编辑
- (void)cassTextViewWillBeginEditing {
    //判断疾病类型是否有选择
    if (self.cassSmallType.length == 0) {
        [self.caseTextView setEditable:NO];
        //弹窗
        [SVProgressHUD showInfoWithStatus:@"请先选择疾病细分"];
        [SVProgressHUD setFadeOutAnimationDuration:0.5];
        [SVProgressHUD setFadeInAnimationDuration:0];
        [SVProgressHUD dismissWithDelay:1];
    }
}


#pragma mark - 代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

        return 2;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier"];
    
    if (nil == cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"reuseIdentifier"];
    }
    //判断第一组的cell的显示
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"疾病类型:";
            if (self.detailText) {
               [cell.detailTextLabel setText:self.detailText];
                self.cassType = self.detailText;
            }else{
                cell.detailTextLabel.text = @"请选择";
            }
            
        }else if(indexPath.row == 1){
            cell.textLabel.text = @"疾病细分:";
            
            if (self.detailText) {
                [cell.detailTextLabel setText:self.detailText];
                self.cassSmallType = self.detailText;
            }else{
                cell.detailTextLabel.text = @"请选择";
            }
        }
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
        //判断第二组的cell的显示
    }else if (indexPath.section == 1){
        
        //取消cell的点击效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //添加cell的自定义view
        NSString * title = nil;
        UIView * contentView = [[UIView alloc]init];
        [cell.contentView addSubview:contentView];

        [contentView makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.right.equalTo(cell.contentView);
            make.width.height.equalTo(cell.contentView);
        }];
        //添加标题label
        UILabel * label = [[UILabel alloc]init];
        label.text = title;
        [contentView addSubview:label];
        
        [label makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(contentView).offset(20);
            make.left.equalTo(contentView).offset(20);
            
        }];
       
        if (indexPath.row == 0) {
            [label setText:@"病症描述:"];
            [contentView addSubview:self.caseTextView];
            
            [self.caseTextView makeConstraints:^(MASConstraintMaker *make) {
                
                make.top.equalTo(label.bottom).offset(10);
                make.left.equalTo(label);
                make.right.equalTo(contentView).offset(-20);
                make.height.equalTo(130);
            }];
            
        }else if (indexPath.row == 1){
            
            [label setText:@"病症照片:"];
            
            UIImageView * imgv_photo = [UIImageView new];
            imgv_photo.image = [UIImage imageNamed:@"compose_pic_add_highlighted"];
            imgv_photo.userInteractionEnabled = YES;
            
            self.imgv_photo = imgv_photo;
            //添加手势
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapPhotoImagView:)];
            [imgv_photo addGestureRecognizer:tap];
            [imgv_photo sizeToFit];
            [contentView addSubview:imgv_photo];
            
            [imgv_photo makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(label.bottom).offset(20);
                make.left.equalTo(label.left).offset(20);
                make.width.height.equalTo(100);
            }];
        }
    }

    return cell;
}


//cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    XGAddCaseVC * addCaseVC = [[XGAddCaseVC alloc]init];
    addCaseVC.delegate = self;
    //当点击第一组时,跳转到其它控制器
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            addCaseVC.title = @"疾病类型";
            addCaseVC.cell1 = YES;
        }else if (indexPath.row == 1){
            //判断疾病类型是否有选择
            if (self.cassType.length == 0) {
                //弹窗
                [SVProgressHUD showInfoWithStatus:@"请先选择疾病类型"];
                [SVProgressHUD setFadeOutAnimationDuration:0.5];
                [SVProgressHUD setFadeInAnimationDuration:0];
                [SVProgressHUD dismissWithDelay:1];
                return;
            }
            addCaseVC.title = @"疾病细分";
            addCaseVC.cell1 = NO;
            [self.caseTextView setEditable:YES];
            [self.tableView reloadData];
        }
        
        //取消cell的选中状态
        UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.selected = NO;
        [self.navigationController pushViewController:addCaseVC animated:YES];
    }else {
        if (indexPath.row == 0) {
            //判断疾病细分是否有选择
            if (self.cassSmallType.length == 0) {
                //弹窗
                [SVProgressHUD showInfoWithStatus:@"请先选择疾病类型"];
                [SVProgressHUD setFadeOutAnimationDuration:0.5];
                [SVProgressHUD setFadeInAnimationDuration:0];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
    }
    
}

- (void)reloadCellsWithDetailString:(NSString *)string andIscell1:(BOOL)iscell1{
    self.detailText = string;
    NSIndexPath * indexPath;
    
    if (iscell1) {
    
        indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    }else{
        indexPath = [NSIndexPath indexPathForItem:1 inSection:0];
    }

    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

//MARK: 获取相册图片的代理方法
- (void)tapPhotoImagView:(UITapGestureRecognizer *)tap {
    
    //判断其它选项是否有选择
    if (self.cassSmallType == nil) {
        //弹窗
        [SVProgressHUD showInfoWithStatus:@"请先选择疾病细分"];
        [SVProgressHUD setFadeOutAnimationDuration:0.5];
        [SVProgressHUD setFadeInAnimationDuration:0];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}
// 当完成照片选择之后, 就会调用该方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    //取出被选中的照片
    UIImage * selectedPhoto = info[UIImagePickerControllerOriginalImage];
    
    [self dismissViewControllerAnimated:YES completion:^{
        [self.imgv_photo setImage:selectedPhoto];
        self.photoName = @"";
    }];
}


//设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return 50;
    }else if (indexPath.section == 1){
        return 200;
    }
    return 44;
}

#pragma mark: - 懒加载
- (NSString *)caseString {
    if (nil == _caseString) {
        _caseString = [NSString string];
    }
    return _caseString;
}

- (UITextView *)caseTextView {
    if (nil == _caseTextView) {
        _caseTextView = [[UITextView alloc]init];
        _caseTextView.backgroundColor = [UIColor lightGrayColor];
    }
    return _caseTextView;
}

- (NSString *)photoName {
    if (nil == _photoName) {
        _photoName = @"compose_pic_add_highlighted";
    }
    return _photoName;
}

//MARK: - 销毁监听者
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end










